// pages/cart/cart.js
let login = require('../../../config/login.js');
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    checkAll: false,
    cartData: null,
    address: '',
    cart_form_data: [],
    spread: false, // 收起展开失效商品
    startX: '',
    startY: '',
    shade: false,
    delivery: '请选择收货地址',
    hiddenLoading: true,
    address_id: '',
    toggle: true,
    partData: {
      imgUrls: '',
      name: '',
      inventory: 0,
      price: '',
      goods_id: '',
      detail:false
    },
  },

  // 收起展开失效商品
  spreadall() {
    const that = this;
    that.setData({
      spreadall: !that.data.spreadall
    })
  },

  // 获取cart_form_data
  getFormData() {
    const that = this;
    let mydata = that.data.cartData.storeList;
    let arr = [];
    mydata.forEach(item => {
      item.cartList.forEach(i => {
        let obj = {
          storeId: item.store_id,
          cartID: i.id,
          goodsNum: i.goods_num,
          selected: i.selected
        }
        arr.push(obj);
      })
    })
    return JSON.stringify(arr);
  },

  // 结算
  toFillOrder(e) {
    const that = this;
    let Storeid = 0;
    let where = e.currentTarget.dataset.where;
    let notSelected = that.data.cartData.storeList.every(item => {
      return item.cartList.every(i => {
        return i.selected == 0
      })
    })
    if (notSelected) {
      app.showInfo("购物车还没有选中商品哟")
      return;
    }
    that.data.cartData.storeList.forEach(item => {
      if (item.store_type == 2) {
        item.cartList.forEach(i => {
          if (i.selected == 1) {
            Storeid = i.store_id
          }
        })
      }
    })
    wx.navigateTo({
      url: `/page/detail/pages/fillOrder/fillOrder?where=${where}&Storeid=${Storeid}`,
    })
  },

  // 获取定位
  location() {
    const that = this;
    wx.navigateTo({
      url: '/page/detail/pages/chooseAddress/chooseAddress?type=2',
    })
  },
  // 加载数据
  newData() {
    const that = this;
    const token = app.globalData.token;
    let json = {
      address_id: app.globalData.addressId ? app.globalData.addressId : 0,
      token: token,
      coordinate: 'GCJ02'
    }

    if (json.address_id > 0) {
      let jsonData = app.utils.getSignData(json); // 添加签名
      app.utils.post(app.api.reqUrls.addresslist, jsonData).then((res) => {
        that.setData({
          hiddenLoading: true
        })
        if (res.status == 1) {
          if (res.result.length > 0) {
            // let arr = res.address.split('|');
            // res.address = (arr[0] || '') + (arr[1] || '')
            that.setData({
              delivery: res.result[0].address
            })
          }
        } else {
          throw res.msg
        }
      }).catch(err => {
        app.showInfo(err.toString())
        that.setData({
          hiddenLoading: true
        })
      })
    }

  },
  // 跳转详情
  toDetail(e) {
    const that = this;
    let id = e.currentTarget.dataset.goodsid;
    wx.navigateTo({
      url: `/page/detail/pages/details/details?id=${id}`,
    })
  },


  // 全选
  pitchAll() {
    const that = this;
    let checkAll = that.data.checkAll;
    let storeList = that.data.cartData.storeList || [];
    let listStates = [];
    storeList.forEach((item, index) => {
      item.checked = !checkAll
      listStates[index] = item.cartList.filter((data) => {
        data.selected = !checkAll
      })
    })

    that.setData({
      [`cartData.storeList`]: storeList,
      checkAll: !checkAll
    })
    that.debounceMyEvents()
  },

  //各店铺全选
  pitch(e) {
    const that = this;
    let storeIndex = e.currentTarget.dataset.storeindex;
    let lists = that.data.cartData.storeList[storeIndex].cartList;
    lists.map((data) => {
      data.selected = that.data.cartData.storeList[storeIndex].checked ? 0 : 1
    })
    let storeList = that.data.cartData.storeList || [];
    let listStates = [];
    storeList.forEach((item, index) => {
      listStates[index] = item.cartList.every((data) => {
        return data.selected
      })
    })
    let checkAll = listStates.every(item => {
      return item
    })
    that.setData({
      [`cartData.storeList[${storeIndex}].checked`]: !that.data.cartData.storeList[storeIndex].checked,
      [`cartData.storeList[${storeIndex}].cartList`]: lists,
      checkAll
    })
    that.debounceMyEvents()
  },

  // 选中一个商品
  switchGoodDetail(e) {
    const that = this;
    let index = e.currentTarget.dataset.index;
    let storeIndex = e.currentTarget.dataset.storeindex;
    let lists = that.data.cartData.storeList[storeIndex].cartList;

    lists[index].selected = lists[index].selected ? 0 : 1;
    let storeList = that.data.cartData.storeList || [];
    let listStates = [];
    storeList.forEach((item, index) => {
      listStates[index] = item.cartList.every((data) => {
        return data.selected
      })
    })
    let checkAll = listStates.every(item => {
      return item
    })
    that.setData({
      [`cartData.storeList[${storeIndex}].cartList`]: lists,
      checkAll
    })
    var boot = lists.some((data) => {
      return !data.selected
    })
    if (boot) {
      that.setData({
        [`cartData.storeList[${storeIndex}].checked`]: false
      })
    } else {
      that.setData({
        [`cartData.storeList[${storeIndex}].checked`]: true
      })
    }
    that.debounceMyEvents()
  },
  debounceMyEvents:app.utils.debounce(function(storeIndex,index){
    var that = this
    that.getAllData(that.getFormData(), storeIndex, index);
  },500),
  // 点击加减
  myevents(e){
    var that = this
    let index = e.currentTarget.dataset.index;
    let storeIndex = e.currentTarget.dataset.storeindex;
    // let count = e.currentTarget.dataset.count;
    let val = e.detail.val;
    that.setData({
      [`cartData.storeList[${storeIndex}].cartList[${index}].goods_num`]: val
    })
    this.debounceMyEvents(storeIndex,index)
  },

  // 跳转到商品详情
  skipDetails(e) {
    let goodsId = e.currentTarget.dataset.goodsid
    wx.navigateTo({
      url: `/page/detail/pages/details/details?id=${goodsId}`

    })
  },

  // 回到首页
  toHome() {
    const that = this;
    wx.switchTab({
      url: '/page/tabBar/index/index',
    })
  },
  //滑动删除
  doDelete(e) {
    const that = this;
    const id = e.currentTarget.dataset.id;
    const token = app.globalData.token;
    let json = {
      ids: id,
      token: token
    }
    let jsonData = app.utils.getSignData(json);
    app.utils.post(app.api.reqUrls.delCart, jsonData).then(res => {
      that.setData({
        hiddenLoading: true
      })
      if (res.status == 1) {
        that.debounceMyEvents();
      }
    }).catch(err => {
      app.showInfo(err.toString())
      that.setData({
        hiddenLoading: true
      })
    })
  },
  // 删除购物车
  delCart() {
    const that = this;
    let notSelected = that.data.cartData.storeList.every(item => {
      return item.cartList.every(i => {
        return i.selected == 0
      })
    })
    if (notSelected) {
      app.showInfo("请选择要删除的商品")
      return;
    }
    let storeList = that.data.cartData.storeList || [];
    let listStates = [];
    storeList.forEach((item, index) => {
      listStates[index] = item.cartList.filter((data) => {
        return data.selected
      })
    })
    let ids = [];
    listStates.forEach((item, index) => {
      item.forEach((i, s) => {
        ids.push(i.id)
      })
    })
    let str = ids.join(',')

    let json = {
      token: app.globalData.token,
      ids: str
    }
    let jsonData = app.utils.getSignData(json);
    wx.showModal({
      title: '',
      content: '是否删除所选商品',
      confirmText: '确定',
      confirmColor: '#ff5151',
      success(res) {
        if (res.confirm) {
          that.setData({
            hiddenLoading: false
          })
          app.utils.post(app.api.reqUrls.delCart, jsonData).then(res => {
            that.setData({
              hiddenLoading: true
            })
            if (res.status == 1) {
              that.debounceMyEvents();
            }
          }).catch(err => {
            app.showInfo(err.toString())
            that.setData({
              hiddenLoading: true
            })
          })
        } else {
          console.log('取消删除')
        }
      }
    })
  },

  // 清除所有失效商品
  clearAllInvalid() {
    const that = this;

    let json = {
      token: app.globalData.token,
      ids: that.data.cartData.invalid_ids
    }
    let jsonData = app.utils.getSignData(json);
    wx.showModal({
      title: '',
      content: '是否清除所有失效商品',
      confirmText: '确定',
      confirmColor: '#ff5151',
      success(res) {
        if (res.confirm) {
          that.setData({
            hiddenLoading: false
          })
          app.utils.post(app.api.reqUrls.delCart, jsonData).then(res => {
            that.setData({
              hiddenLoading: true
            })
            if (res.status == 1) {
              that.getAllData();
            }
          }).catch(err => {
            app.showInfo(err.toString())
            that.setData({
              hiddenLoading: true
            })
          })
        } else {
          console.log('取消删除')
        }
      }
    })

  },

  // 添加到购物车
  // addToCart(e) {
  //   const that = this;
  //   app.checkUserInfoAuthorizationCart().then(() => {
  //     let goodsid = e.currentTarget.dataset.goodsid;
  //     let token = app.globalData.token;
  //     let json = {
  //       token,
  //       goods_num: 1,
  //       goods_id: goodsid,
  //     }
  //     let jsonData = app.utils.getSignData(json);
  //     that.setData({
  //       hiddenLoading: false
  //     })
  //     app.utils.post(app.api.reqUrls.addCart, jsonData).then(res => {
  //       that.setData({
  //         hiddenLoading: true
  //       })
  //       if (res.status == 1) {
  //         // 添加成功
  //         wx.showToast({
  //           title: '已添加到购物车',
  //           icon: 'success',
  //           duration: 1000
  //         })
  //         that.getAllData();
  //       } else {
  //         throw res.msg
  //       }
  //     }).catch(err => {
  //       app.showInfo(err.toString())
  //       that.setData({
  //         hiddenLoading: true
  //       })
  //     })
  //   })

  // },
  /**
   * 手指触摸动作开始 记录起点X坐标
   */
  touchstart: function (e) {
    //开始触摸时 重置所有删除
    this.data.cartData.storeList.forEach(data => {
      data.cartList.forEach(function (v, i) {
        if (v.isTouchMove)
          //只操作为true的
          v.isTouchMove = false;
      });
    })

    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      cartData: this.data.cartData
    });
  },
  /**
   * 滑动事件处理
   */
  touchmove: function (e) {
    var that = this,
      id = e.currentTarget.dataset.id, //当前索引
      startX = that.data.startX, //开始X坐标
      startY = that.data.startY, //开始Y坐标
      touchMoveX = e.changedTouches[0].clientX, //滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY, //滑动变化坐标
      //获取滑动角度
      angle = that.angle({
        X: startX,
        Y: startY
      }, {
        X: touchMoveX,
        Y: touchMoveY
      });
    this.data.cartData.storeList.forEach(data => {
      data.cartList.forEach(function (v, i) {
        v.isTouchMove = false;
        //滑动超过30度角 return
        if (Math.abs(angle) > 30) return;
        if (v.id == id) {
          if (touchMoveX > startX)
            //右滑
            v.isTouchMove = false;
          //左滑
          else v.isTouchMove = true;
        }
      });
    })
    //更新数据
    that.setData({
      cartData: this.data.cartData
    });
  },
  /**
   * 计算滑动角度
   */
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y;
    //返回角度 /Math.atan()返回数字的反正切值
    return (360 * Math.atan(_Y / _X)) / (2 * Math.PI);
  },
  // 获取数据（不传cart_form_data） || 提交选中状态（传cart_form_data）
  getAllData(cart_form_data = [], storeIndex, index) {
    const that = this;
    let json = {
      token: app.globalData.token,
      cart_form_data,
      address_id: app.globalData.addressId ? app.globalData.addressId : '0',
    }
    let jsonData = app.utils.getSignData(json);
    that.setData({
      hiddenLoading: false
    })
    app.utils.post(app.api.reqUrls.cartList, jsonData).then(res => { // 获取购物车列表
      setTimeout(() => {
        wx.stopPullDownRefresh()
      }, 1000)
      wx.nextTick(() => {
        that.setData({
          hiddenLoading: true
        })
      })
      if (res.status == 1) {
        res.result.storeList.forEach(item => {
          app.getImg(item.cartList);
          let checked = item.cartList.every(i => { // 检测商店全选状态
            return i.selected
          })
          item.checked = checked;
        })
        let checkAll = res.result.storeList.every(item => { // 检测全选状态
          return item.checked;
        })
        app.getImg(res.result.like_goods); // 获取推荐商品缩略图
        app.getImg(res.result.invalid_list); // 获取失效商品缩略图
        res.result.storeList.forEach(data => {
          data.cartList.forEach(res => {
            res.isTouchMove = false; //是否滑动
          })
        })
        that.setData({
          cartData: res.result,
          checkAll
        })
        app.getCartCount();
      } else if (res.status == 0) {
        app.showInfo(res.msg);
        if (index != undefined && storeIndex != undefined) {
          that.setData({
            [`cartData.storeList[${storeIndex}].cartList[${index}].goods_num`]: res.result.limit_num
          })
        }
      } else {
        throw res.msg
      }
    }).catch(err => {
      app.showInfo(err.toString())
      that.setData({
        hiddenLoading: true
      })
      setTimeout(() => {
        wx.stopPullDownRefresh()
      }, 1000)
    })
  },
// 点击添加购物车
addShowCart(e) {
  const that = this;
  console.log(e, 78787)
  let goods = e.currentTarget.dataset.goods
  that.setData({
    toggle: false,
    'partData.imgUrls': goods.img,
    'partData.name': goods.goods_name,
    'partData.inventory': goods.store_count,
    'partData.price': goods.shop_price,
    'partData.goods_id': goods.goods_id,
  })
},
// 添加到购物车
addToCart(e) {
  app.checkUserInfoAuthorizationCart().then(() => {
    const that = this;
    let token = app.globalData.token;
    let json = {
      token,
      goods_num: e.detail,
      goods_id: that.data.partData.goods_id,
    }
    let jsonData = app.utils.getSignData(json);
    app.utils.post(app.api.reqUrls.addCart, jsonData).then(res => {
      if (res.status == 1) {
        wx.showToast({
          title: '添加成功',
          icon: 'success',
          duration: 2000
        })
        that.getAllData()
        app.getCartCount();
        app.cartCountCallback = (res) => {
          that.setData({
            cartCount: res
          })
        }
      } else {
        throw res.msg
      }
    }).catch(err => {
      app.showInfo(err.toString())
    })

  })
},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this;
    that.setData({
      toggle: true,
    })
  },
  initPage() {
    const that = this;
    that.setData({
      hiddenLoading: false,
      shade: app.globalData.shade,
      address: app.globalData.address
    })

    that.getAllData();
    if (app.globalData.addressId) {
      that.newData()
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const that = this;
    login.checkLogin().then(res => {
      that.initPage()
    }).catch(err => {
      app.appCallBack = (e) => {
        that.initPage()
      }
    })

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.initPage()
  },


  onHide() {
    const that = this;
    that.setData({
      toggle: true,
    })
  }
})